package flc.ast.activity;

import android.app.Dialog;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.CutAdapter;
import flc.ast.bean.MyCutBean;
import flc.ast.databinding.ActivityVideoTailorBinding;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.CutView;

public class VideoTailorActivity extends BaseAc<ActivityVideoTailorBinding> implements MediaPlayer.OnPreparedListener {

    public static String videoPath;
    private CutAdapter cutAdapter;
    private int oldPosition = 0;
    protected int mVideoOriWidth = -1;
    protected int mVideoOriHeight = -1;
    private long videoLength;
    private Dialog myTipDialog;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideoPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_video_tailor;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoTailorBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.videoView.setOnPreparedListener(this);
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.tvVideoTailorSave.setOnClickListener(this);
        mDataBinding.rvVideoTailorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        cutAdapter = new CutAdapter();
        mDataBinding.rvVideoTailorList.setAdapter(cutAdapter);
        cutAdapter.setOnItemClickListener(this);
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvVideoTailorSave:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        cutAdapter.getItem(oldPosition).setSelect(false);
        cutAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        cutAdapter.getItem(position).setSelect(true);
        cutAdapter.notifyItemChanged(position);
        setView(position);
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                mDataBinding.cutView.setMargin(mDataBinding.videoView.getLeft(), mDataBinding.videoView.getTop(),
                        mDataBinding.videoView.getRight() - mDataBinding.videoView.getWidth(), mDataBinding.videoView.getBottom() - mDataBinding.videoView.getHeight());
            }
        });
        //裁剪数据
        List<MyCutBean> listTailor = new ArrayList<>();
        listTailor.add(new MyCutBean(getString(R.string.img_text), R.drawable.yuanshi0, R.drawable.yuanshi9, -1f, true));
        listTailor.add(new MyCutBean("1:1", R.drawable.shape_cut2, R.drawable.shape_cut, 1f, false));
        listTailor.add(new MyCutBean("1:2", R.drawable.cut1v2b, R.drawable.cut1v2a, 1f / 2f, false));
        listTailor.add(new MyCutBean("1:3", R.drawable.cut1v3b, R.drawable.cut1v3a, 1f / 3f, false));
        listTailor.add(new MyCutBean("2:3", R.drawable.cut2v3b, R.drawable.cut2v3a, 2f / 3f, false));
        listTailor.add(new MyCutBean("3:4", R.drawable.cut3v4b, R.drawable.cut3v4a, 3f / 4f, false));
        cutAdapter.setList(listTailor);
    }

    //剪切视频
    private void saveVideo() {
        Rect rect = getCropValueInfo();
        EditorHolder.editor().videoCrop(videoPath, rect.right, rect.bottom,
                rect.left, rect.top, new IEditorListener() {
                    @Override
                    public void onSuccess(String outFilePath) {
                        dismissDialog();
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                        ToastUtils.showShort(R.string.save_suc);
                        startActivity(HomeActivity.class);
                    }

                    @Override
                    public void onFailure(String errMsg) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.cut_def);
                    }

                    @Override
                    public void onProgress(int progress) {
                        showDialog(getString(R.string.save_video_ing) + progress + "%");
                    }
                });
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.tvVideoLeftText.setText("00:00");
        mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideoPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.sbVideoPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoLeftText.setText("00:00");
                mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
                mDataBinding.sbVideoPlay.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                mp.seekTo(1);
                stopTime();
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
        mDataBinding.videoView.pause();
        stopTime();
    }

    //设置裁剪框
    private void setView(int position) {
        //计算一下
        int left = mDataBinding.videoView.getLeft();
        int right = mDataBinding.videoView.getRight() - mDataBinding.videoView.getWidth();
        int top = mDataBinding.videoView.getTop();
        int bottom = mDataBinding.videoView.getBottom() - mDataBinding.videoView.getHeight();
        switch (position) {
            case 0://原图
                break;
            case 1://1:1
                left = 100;
                top = 100;
                right = 100;
                bottom = 100;
                break;
            case 2://1:2
                left = 200;
                top = 100;
                right = 200;
                bottom = 100;
                break;
            case 3://1:3
                left = 300;
                top = 100;
                right = 300;
                bottom = 100;
                break;
            case 4://2:3
                left = 150;
                top = 100;
                right = 150;
                bottom = 100;
                break;
            case 5://3:4
                left = 120;
                top = 100;
                right = 120;
                bottom = 100;
                break;
        }
        mDataBinding.cutView.setMargin(left, top, right, bottom);
    }

    private Rect getCropValueInfo() {
        CutView cutView = mDataBinding.cutView;
        float[] cutArr = cutView.getCutArr();
        float left = cutArr[0];
        float top = cutArr[1];
        float right = cutArr[2];
        float bottom = cutArr[3];
        int cutWidth = cutView.getRectWidth();
        int cutHeight = cutView.getRectHeight();

        //计算宽高缩放比
        float leftPro = left / cutWidth;
        float topPro = top / cutHeight;
        float rightPro = right / cutWidth;
        float bottomPro = bottom / cutHeight;

        //得到裁剪位置
        int cropWidth = (int) (mVideoOriWidth * (rightPro - leftPro));
        int cropHeight = (int) (mVideoOriHeight * (bottomPro - topPro));
        int x = (int) (leftPro * mVideoOriWidth);
        int y = (int) (topPro * mVideoOriHeight);

        return new Rect(x, y, cropWidth, cropHeight);
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoOriWidth = mp.getVideoWidth();
        Log.e("TAG", "onPrepared: "+mVideoOriWidth );
        mVideoOriHeight = mp.getVideoHeight();
    }
}